/*
 * Copyright 2009 (c) Patrick Pietens.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package indigo.service.services 
{
	import indigo.service.errors.ServiceError;
	import indigo.service.events.ServiceEvent;
	import indigo.utils.DisposableEventDispatcher;
	import indigo.utils.IDisposable;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TextEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	/**
	 * Executes when the Service responds successfully
	 */
	[Event(name="serviceResult", type="indigo.events.ServiceEvent")]

	/**
	 * Executes when the Service responds with an error
	 */
	[Event(name="serviceFault", type="indigo.events.ServiceEvent")]	
	/**
	 * The HTTPService class is used to send an load data to an HTTP remote service. 
	 * It is recommend to use the sendAndLoadHTTP shortcut. 
	 * 
	 */	
	public class HTTPService extends DisposableEventDispatcher implements IDisposable, IService
	{
		/**
		 * URLLoader that is used to make the IService call
		 */
		protected var _loader:URLLoader;
		/**
		 * URLRequest that is used to make the IService call
		 */
		protected var _request:URLRequest;
		/**
		 * URLVariables send with the request
		 */
		public var urlVariables:URLVariables;

		/**
		 * Constructor
		 * @param	Location of the IService
		 * @param	Method that is used to send data to IService
		 * 
		 */
		public function HTTPService( url:String = null, method:String = URLRequestMethod.POST )
		{
			// Create the URLRequest
			this._request = new URLRequest( url );
			this._request.method = method;
			
			// Create the Loader
			this._loader = new URLLoader( );
			this._loader.addEventListener( Event.COMPLETE, this.onResult );
			this._loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, this.onFault );			
			this._loader.addEventListener( IOErrorEvent.IO_ERROR, this.onFault );
		}

		
		/**
		 * Executes the IService
		 * @param	Arguments send to the IService
		 * 
		 */
		public function sendAndLoad( ...args ):void
		{
			this._request.data = this.urlVariables;
			this._loader.load( this._request );
		}

		
		/**
		 * Executes when the IService responds succesfully
		 * @param	Event which triggers the method
		 * 
		 */
		protected function onResult( event:Event ):void
		{
			// Close the connection
			this._loader.close( );
			
			// Dispatch event
			var myEvent:ServiceEvent = new ServiceEvent( ServiceEvent.RESULT );
			myEvent.data = this._loader.data;
			this.dispatchEvent( myEvent );
		}

		
		/**
		 * Executes when an error occured while executing the IService
		 * @param	Event which triggers the method
		 * 
		 */
		protected function onFault( event:TextEvent ):void
		{
			// Dispatch event
			if ( this.hasEventListener( ServiceEvent.FAULT ) )
			{
				var myEvent:ServiceEvent = new ServiceEvent( ServiceEvent.FAULT );
				myEvent.errorCode = event.type;
				myEvent.errorMessage = event.text;
				this.dispatchEvent( myEvent );
			}
			
			// Otherwise throw an error
			else
				throw new ServiceError( ServiceError.SERVICE_EXCEPTION + ": " + event.text );
		}

		
		/**
		 * URLLoader that is used to make the IService call
		 * 
		 */		
		public function get loader():URLLoader
		{
			return this._loader;
		}

		
		/**
		 * String that indicates the location of the IService
		 * 
		 */		
		public function set url( value:String ):void
		{
			this._request.url = value;
		}

		
		/**
		 * String that indicates the location of the IService
		 * 
		 */		
		public function get url():String
		{
			return this._request.url;		
		}

		
		/**
		 * String that indicates the post method of the IService
		 * 
		 */
		public function set method( value:String ):void
		{
			this._request.method = value;		
		}

		
		/**
		 * String that indicates the post method of the IService
		 * 
		 */
		public function get method():String
		{
			return this._request.method;		
		}

		
		/**
		 * @inheritDoc
		 * 
		 */
		override public function dispose( event:Event = null ):void
		{
			super.dispose( event );
			
			if ( this._loader )
			{
				//				this._loader.close( );
				
				// Remove listeners
				this._loader.removeEventListener( Event.COMPLETE, this.onResult );
				this._loader.removeEventListener( SecurityErrorEvent.SECURITY_ERROR, this.onFault );			
				this._loader.removeEventListener( IOErrorEvent.IO_ERROR, this.onFault );
			}
			
			// Nullify properties
			this._loader = null;
			this._request = null;
		}
	}
}